package com.thb.message.service.Impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.thb.message.dao.IMessageDao;
import com.thb.message.memcached.MKUtils;
import com.thb.message.model.Message;
import com.thb.message.service.IMessageService;
import com.thb.push.util.PushUtils;
import com.thb.utils.Page;

@Service
public class MessageServiceImpl implements IMessageService {
	
	@Autowired
	private IMessageDao messageDao;

	@Override
	public int addMessage(String content, int type, String fromUid, String toUid) {
		Date now = new Date();
		Message message = new Message();
		message.setContent(content);
		message.setRecvUserId(toUid);
		message.setSendUserId(fromUid);
		message.setType(type);
		message.setTime(now);
		message.setStatus(0);
		int k = messageDao.addMessage(message);
//		MemcachedUtil.remove(MKUtils.getPersionMessageKey(toUid));
		PushUtils.sendTagMessage(toUid, content);
		return k;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<JSONObject> findByTime(Date date,String uid) {
		
		List<Message> mList = new ArrayList<Message>();
		List<Message> rList = new ArrayList<Message>();
		
//		Object o = MemcachedUtil.get(MKUtils.getPersionMessageKey(uid));
//		if( o!= null && !(o instanceof NullObject)){
//			mList = (List<Message>)o;
//		}else if(o == null){
//			mList = messageDao.findByUser(uid);
//			MemcachedUtil.set(MKUtils.getPersionMessageKey(uid), mList.size()>0?mList:NullObject.nullObject);
//		}
		
		int count = 0;
		
		for(Message me:mList){
			if(date == null){
				if(count < Page.pageSize ){
					rList.add(me);
					count = count + 1;
				}
				break;
			}else{
				if(date.before(me.getTime())){
					if(count < Page.pageSize ){
						rList.add(me);
						count = count + 1;
					}
					break;
				}
			}
		}
		
		return toJsonObject(rList);
	}
	
	private List<JSONObject> toJsonObject(List<Message> rList){
		List<JSONObject> oList = new ArrayList<JSONObject>();
		for(Message m:rList){
			JSONObject o = new JSONObject();
			
			o.put("messageType", m.getType());
			o.put("messageTitle", m.getContent().substring(0, m.getContent().length() > 20 ? 20 :  m.getContent().length() - 1));
			
			o.put("messageContent", m.getContent());
			o.put("messageTime", m.getTime());
			
			oList.add(o);
		}
		return oList;
	}

}
